<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html>
<head>
<title>Menus and toolbars in Java Swing</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="Java, Swing, menus, toolbars, tutorial, programming, Linux">
<meta name="description" content="This part of the Java Swing tutorial, we work with menus and 
toolbars in Java Swing.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<div class="content">


<a href="/" title="Home">Home</a>&nbsp;
<a href=".." title="Home">Contents</a>


<h1>Menus and toolbars in Java Swing</h1>



<p>
A menubar is one of the most visible parts of the GUI application. It is a group of 
commands located in various menus. While in console applications you had to remember 
all those arcane commands, here we have most of the commands grouped into logical parts. 
There are accepted standards that further reduce the amount of time spending to learn
a new application.
</p>

<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* NewSquare */
google_ad_slot = "0364418177";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script>

<p>
In Java Swing, to implement a menubar, we use three objects. A <code>JMenuBar</code>, a 
<code>JMenu</code> and a <code>JMenuItem</code>.
</p>


<h2>Simple menu</h2>

<p>
We begin with a simple menubar example. 
</p>

<pre class="code">
package zetcode;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.SwingUtilities;


public class Example extends JFrame {

    public Example() {
        initUI();
    }

    public final void initUI() {

        JMenuBar menubar = new JMenuBar();
        ImageIcon icon = new ImageIcon(getClass().getResource("exit.png"));

        JMenu file = new JMenu("File");
        file.setMnemonic(KeyEvent.VK_F);

        JMenuItem eMenuItem = new JMenuItem("Exit", icon);
        eMenuItem.setMnemonic(KeyEvent.VK_C);
        eMenuItem.setToolTipText("Exit application");
        eMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                System.exit(0);
            }

        });

        file.add(eMenuItem);

        menubar.add(file);

        setJMenuBar(menubar);

        setTitle("Simple menu");
        setSize(300, 200);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                Example ex = new Example();
                ex.setVisible(true);
            }
        });
    }
}
</pre>

<p>
Our example will show a menu with one item. Selecting the exit menu item we close the application. 
</p>

<pre class="explanation">
JMenuBar menubar = new JMenuBar();
</pre>

<p>
Here we create a menubar. 
</p>

<pre class="explanation">
ImageIcon icon = new ImageIcon(getClass().getResource("exit.png"));
</pre>

<p>
We will display an icon in the menu. 
</p>

<pre class="explanation">
JMenu file = new JMenu("File");
file.setMnemonic(KeyEvent.VK_F);
</pre>

<p>
We create a menu object. The menus can be accessed via the keybord as well. 
To bind a menu to a particular key, we use the <code>setMnemonic()</code> 
method. In our case, the menu can be opened with the <b>ALT + F</b> shortcut.
</p>

<pre class="explanation">
fileClose.setToolTipText("Exit application");
</pre>

<p>
This code line creates a tooltip for a menu item.
</p>


<img src="/img/gui/javaswing/simplemenu.png" alt="Simple menu">
<div class="figure">Figure: Simple menu</div>


<h2>Submenu</h2>

<p>
Each menu can also have a submenu. This way we can group similar commnads into groups. 
For example we can place commands that hide/show various toolbars like personal bar, 
address bar, status bar or navigation bar into a submenu called toolbars. Within a menu, 
we can seperate commands with a separator. It is a simple line. It is common practice 
to separate commands like new, open, save from commands like print, print preview with 
a single separator.  Menus commands can be launched via keyboard shortcuts. For this, 
we define menu item accelerators.
</p>


<pre class="code">
package zetcode;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;


public class Example extends JFrame {

    public Example() {
        initUI();
    }

    public final void initUI() {

        JMenuBar menubar = new JMenuBar();
        ImageIcon iconNew = new ImageIcon(getClass().getResource("new.png"));
        ImageIcon iconOpen = new ImageIcon(getClass().getResource("open.png"));
        ImageIcon iconSave = new ImageIcon(getClass().getResource("save.png"));
        ImageIcon iconExit = new ImageIcon(getClass().getResource("exit.png"));

        JMenu file = new JMenu("File");
        file.setMnemonic(KeyEvent.VK_F);

        JMenu imp = new JMenu("Import");
        imp.setMnemonic(KeyEvent.VK_M);

        JMenuItem newsf = new JMenuItem("Import newsfeed list...");
        JMenuItem bookm = new JMenuItem("Import bookmarks...");
        JMenuItem mail = new JMenuItem("Import mail...");

        imp.add(newsf);
        imp.add(bookm);
        imp.add(mail);

        JMenuItem fileNew = new JMenuItem("New", iconNew);
        fileNew.setMnemonic(KeyEvent.VK_N);

        JMenuItem fileOpen = new JMenuItem("Open", iconOpen);
        fileNew.setMnemonic(KeyEvent.VK_O);

        JMenuItem fileSave = new JMenuItem("Save", iconSave);
        fileSave.setMnemonic(KeyEvent.VK_S);

        JMenuItem fileExit = new JMenuItem("Exit", iconExit);
        fileExit.setMnemonic(KeyEvent.VK_C);
        fileExit.setToolTipText("Exit application");
        fileExit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W,
            ActionEvent.CTRL_MASK));

        fileExit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                System.exit(0);
            }

        });

        file.add(fileNew);
        file.add(fileOpen);
        file.add(fileSave);
        file.addSeparator();
        file.add(imp);
        file.addSeparator();
        file.add(fileExit);

        menubar.add(file);

        setJMenuBar(menubar);

        setTitle("Submenu");
        setSize(360, 250);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                Example ex = new Example();
                ex.setVisible(true);
            }
        });
    }
}
</pre>

<p>
In this example, we create a submenu, a menu separator and an accelerator key.
</p>


<pre class="explanation">
JMenu imp = new JMenu("Import");
...
file.add(imp);
</pre>

<p>
A submenu is just like any other normal menu. It is created the same way. 
We simply add a menu to existing menu. 
</p>

<pre class="explanation">
fileExit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W,
    ActionEvent.CTRL_MASK));
</pre>

<p>
An accelerator is a key shortcut that launches a menu item. In our case, 
by pressing <b>Ctrl + W</b> we close the application.
</p>

<pre class="explanation">
file.addSeparator();
</pre>

<p>
A separator is a horizontal line that visually separates the menu items. 
This way we can group items into some logical places.
</p>

<img src="/img/gui/javaswing/submenu.png" alt="Submenu">
<div class="figure">Figure: Submenu</div>



<h2>JCheckBoxMenuItem</h2>

<p>
A menu item that can be selected or deselected. If selected, the menu item 
typically appears with a checkmark next to it. If unselected or deselected, 
the menu item appears without a checkmark. Like a regular menu item, a check 
box menu item can have either text or a graphic icon associated with it, or both.
</p>

<pre class="code">
package zetcode;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

import javax.swing.BorderFactory;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.SwingUtilities;
import javax.swing.border.EtchedBorder;


public class Example extends JFrame {

    private JLabel statusbar;

    public Example() {
        initUI();
    }

    public final void initUI() {

        JMenuBar menubar = new JMenuBar();
        JMenu file = new JMenu("File");
        file.setMnemonic(KeyEvent.VK_F);

        JMenu view = new JMenu("View");
        view.setMnemonic(KeyEvent.VK_V);

        JCheckBoxMenuItem sbar = new JCheckBoxMenuItem("Show StatuBar");
        sbar.setState(true);

        sbar.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
              if (statusbar.isVisible()) {
                  statusbar.setVisible(false);
              } else {
                  statusbar.setVisible(true);
              }
            }

        });

        view.add(sbar);

        menubar.add(file);
        menubar.add(view);

        setJMenuBar(menubar);

        statusbar = new JLabel(" Statusbar");
        statusbar.setBorder(BorderFactory.createEtchedBorder(
                EtchedBorder.RAISED));
        add(statusbar, BorderLayout.SOUTH);

        setTitle("JCheckBoxMenuItem");
        setSize(360, 250);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                Example ex = new Example();
                ex.setVisible(true);
            }
        });
    }
}
</pre>

<p>
The example shows a <code>JCheckBoxMenuItem</code>. By selecting 
the menu item, we toggle the visibility of 
the statusbar.
</p>

<pre class="explanation">
JCheckBoxMenuItem sbar = new JCheckBoxMenuItem("Show StatuBar");
sbar.setState(true);
</pre>

<p>
We create the  <code>JCheckBoxMenuItem</code> and check it by default. 
The statusbar is initially visible.
</p>

<pre class="explanation">
if (statusbar.isVisible()) {
      statusbar.setVisible(false);
} else {
      statusbar.setVisible(true);
}
</pre>

<p>
Here we toggle the visibility of the statusbar. 
</p>

<pre class="explanation">
statusbar = new JLabel(" Statusbar");
statusbar.setBorder(BorderFactory.createEtchedBorder(
        EtchedBorder.RAISED));
</pre>

<p>
The statusbar is a simple <code>JLabel</code> component. We put a 
raised <code>EtchedBorder</code> around the label, so that it is visible. 
</p>


<img src="/img/gui/javaswing/checkboxmenuitem.png" alt="JCheckBoxMenuItem">
<div class="figure">Figure: JCheckBoxMenuItem</div>


<h2>A popup menu</h2>

<p>
Another type of a menu is a popup menu. It is sometimes called a context menu. 
It is usually shown, when we right click on a component. The idea is to provide 
only the commands, that are relevant to the current context. Say we have an image. 
By right clicking on the image, we get a window with commands to save, rescale, 
move etc the image. 
</p>


<pre class="code">
package zetcode;

import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;


public class PopupMenu extends JFrame
{

    private JPopupMenu menu;
    private Toolkit toolkit;

    public PopupMenu(String title)
    {
        super(title);
        this.initUI();
    }

    private void initUI()
    {
        toolkit = this.getToolkit();

        menu = new JPopupMenu();
        JMenuItem menuItemBeep = new JMenuItem("Beep");

        menuItemBeep.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                toolkit.beep();
            }
        });

        menu.add(menuItemBeep);

        JMenuItem menuItemClose = new JMenuItem("Close");
        menuItemClose.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                System.exit(0);
            }
        });

        menu.add(menuItemClose);

        this.addMouseListener(new MouseAdapter()
        {
            @Override
            public void mouseReleased(MouseEvent e)
            {
                if (e.getButton() == MouseEvent.BUTTON3)
                {
                    menu.show(e.getComponent(), e.getX(), e.getY());
                }
            }
        });

        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setSize(250, 200);
        this.setLocationRelativeTo(null);
    }

    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                PopupMenu pm = new PopupMenu("JPopupMenu");
                pm.setVisible(true);
            }
        });

    }
}
</pre>

<p>
Our example shows a demonstrational popup menu with two commands. The first 
option of the popup menu will beep a sound, the second one will close the window.
</p>

<p>
In our example, we create a submenu, menu separators and create an accelerator key.
</p>

<pre class="explanation">
menu = new JPopupMenu();
</pre>

<p>
To create a popup menu, we have a class called <code>JPopupMenu</code>.
</p>

<pre class="explanation">
JMenuItem menuItemBeep = new JMenuItem("Beep");
</pre>

<p>
The menu item is the same, as with the standard <code>JMenu</code>
</p>

<pre class="explanation">
  this.addMouseListener(new MouseAdapter()
  {
      @Override
      public void mouseReleased(MouseEvent e)
      {
          if (e.getButton() == MouseEvent.BUTTON3)
          {
              menu.show(e.getComponent(), e.getX(), e.getY());
          }
      }
  });
</pre>

<p>
The popup menu is shown, where we clicked with the mouse button. The 
<b>MouseEvent.BUTTON3</b> constant is here to enable
the popup menu only for the mouse right click.
</p>


<img src="/img/gui/javaswing/popupmenu.png" alt="Popup menu">
<div class="figure">Figure: Popup menu</div>



<h2>JToolbar</h2>

<p>
Menus group commands that we can use in an application. Toolbars provide a quick access 
to the most frequently used commands. In Java Swing, the <code>JToolBar</code> 
class creates a toolbar in an application.
</p>

<pre class="code">
package zetcode;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;


public class Example extends JFrame {

    public Example() {
        initUI();
    }

    public final void initUI() {

        JMenuBar menubar = new JMenuBar();
        JMenu file = new JMenu("File");
        menubar.add(file);
        setJMenuBar(menubar);

        JToolBar toolbar = new JToolBar();

        ImageIcon icon = new ImageIcon(getClass().getResource("exit.png"));

        JButton exitButton = new JButton(icon);
        toolbar.add(exitButton);
        exitButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                System.exit(0);
            }

        });

        add(toolbar, BorderLayout.NORTH);

        setTitle("Simple toolbar");
        setSize(300, 200);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                Example ex = new Example();
                ex.setVisible(true);
            }
        });
    }
}
</pre>

<p>
The example creates a toolbar with one exit button.
</p>

<pre class="explanation">
JToolBar toolbar = new JToolBar();
</pre>

<p>
This is the <code>JToolBar</code> constructor.
</p>

<pre class="explanation">
JButton exitButton = new JButton(icon);
toolbar.add(exitButton);
</pre>

<p>
We create a button and add it to the toolbar.
</p>

<img src="/img/gui/javaswing/simpletoolbar.png" alt="Simple toolbar">
<div class="figure">Figure: Simple toolbar</div>


<h2>Toolbars</h2>

<p>
Say, we wanted to create two toolbars. The next example shows, how we could do it.
</p>

<pre class="code">
package zetcode;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;


public class Example extends JFrame {

    public Example() {
        initUI();
    }

    public final void initUI() {

        JToolBar toolbar1 = new JToolBar();
        JToolBar toolbar2 = new JToolBar();

        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

        ImageIcon newi = new ImageIcon(
                getClass().getResource("new.png"));
        ImageIcon open = new ImageIcon(
                getClass().getResource("open.png"));
        ImageIcon save = new ImageIcon(
                getClass().getResource("save.png"));
        ImageIcon exit = new ImageIcon(
                getClass().getResource("exit.png"));

        JButton newb = new JButton(newi);
        JButton openb = new JButton(open);
        JButton saveb = new JButton(save);

        toolbar1.add(newb);
        toolbar1.add(openb);
        toolbar1.add(saveb);
        toolbar1.setAlignmentX(0);

        JButton exitb = new JButton(exit);
        toolbar2.add(exitb);
        toolbar2.setAlignmentX(0);

        exitb.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                System.exit(0);
            }

        });

        panel.add(toolbar1);
        panel.add(toolbar2);

        add(panel, BorderLayout.NORTH);

        setTitle("Toolbars");
        setSize(360, 250);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                Example ex = new Example();
                ex.setVisible(true);
            }
        });
    }
}
</pre>

<p>
We show only one way, how we could create toolbars. Of course, there 
are several possibilities. We put a <code>JPanel</code> to the north of 
the <code>BorderLayout</code> manager. The panel has a vertical
<code>BoxLayout</code>. We add the two toolbars into this panel.
</p>

<pre class="explanation">
JToolBar toolbar1 = new JToolBar();
JToolBar toolbar2 = new JToolBar();
</pre>

<p>
Creation of two toolbars.
</p>

<pre class="explanation">
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
</pre>

<p>
The panel has a vertical <code>BoxLayout</code>. 
</p>

<pre class="explanation">
toolbar1.setAlignmentX(0);
</pre>

<p>
The toolbar is left aligned.
</p>


<pre class="explanation">
panel.add(toolbar1);
panel.add(toolbar2);

add(panel, BorderLayout.NORTH);
</pre>

<p>
We add the toolbars to the panel. Finally, the panel is located into the 
north part of the frame.
</p>

<img src="/img/gui/javaswing/toolbars.png" alt="Toolbars">
<div class="figure">Figure: Toolbars</div>


<p>
In this part of the Java Swing tutorial, we have mentioned menus and
toolbars.
</p>

<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div> 
<br>



<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡ 
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified December 4, 2010  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

